class List {
    constructor() {
        this.url = "http://localhost/ic/goods/data/goods.json";
        this.rightbox = document.querySelector(".rightbox");
        // this.buyit = document.querySelector("#buyit");


        this.load();
        this.addEvent();

    }
    load() {
        ajaxGet(this.url, (res) => {
            // console.log(res);
            this.res = JSON.parse(res);
            this.display();
            // console.log(this.res)
        })
    }
    display() {
        let str = "";
        for (let i = 0; i < this.res.length; i++) {
            str += `<div class="small">
            <p><img src="${this.res[i].url}" alt=""></p>
            <p>${this.res[i].name}</p>
            <p>
                单价：
                <span>${this.res[i].price}</span>
            </p>
            <button class="purc" id="buyit" index="${this.res[i].goodsId}">
                购买
            </button>
        </div>`;
        }
        this.rightbox.innerHTML = str;
        // console.log(this.res)
        // this.buyit = document.querySelector(".purc")
        // console.log(this.buyit)
        // this.buyit = document.querySelector("#buyit");

    }
    addEvent() {

        var that = this;
        this.rightbox.addEventListener("click", function(eve) {
            var eve = eve || window.event;
            if (eve.target.id == "buyit") {

                that.id = eve.target.getAttribute("index");
                // console.log(eve.target)
                that.setData();

            }
        });
    }
    setData() {
        this.goodsMsg = getCookie("goodsMsg") ? JSON.parse(getCookie("goodsMsg")) : [];
        console.log(this.goodsMsg)

        if (this.goodsMsg.length < 1) {
            this.goodsMsg.push({
                id: this.id,
                num: 1
            });
        } else {
            let i;
            let onoff = this.goodsMsg.some((val, idx) => {
                i = idx;
                return val.id === this.id;
            })
            if (onoff) {
                this.goodsMsg[i].num++
            } else {
                this.goodsMsg.push({
                    id: this.id,
                    num: 1
                })
            }
        }
        setCookie("goodsMsg", JSON.stringify(this.goodsMsg));
    }
}
new List();